// controllers/categoryController.js
const pool = require('../config/db');
const { sendResponse } = require('../utils/response');

// 获取所有分类
const getAllCategories = async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT * FROM categories');
    sendResponse(res, 200, '获取分类成功', rows);
  } catch (error) {
    sendResponse(res, 500, '获取分类失败', error.message);
  }
};

// 获取单个分类
const getCategoryById = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.execute('SELECT * FROM categories WHERE id = ?', [id]);
    if (rows.length === 0) {
      return sendResponse(res, 404, '分类未找到');
    }
    sendResponse(res, 200, '获取分类成功', rows[0]);
  } catch (error) {
    sendResponse(res, 500, '获取分类失败', error.message);
  }
};

// 创建分类
const createCategory = async (req, res) => {
  const { name, sort_order, type } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute(
      'INSERT INTO categories (name, sort_order, type) VALUES (?, ?, ?)',
      [name, sort_order || 0, type || 't_main']
    );
    await connection.commit();
    sendResponse(res, 201, '创建分类成功', { id: result.insertId });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '创建分类失败', error.message);
  } finally {
    connection.release();
  }
};

// 更新分类
const updateCategory = async (req, res) => {
  const { id } = req.params;
  const { name, sort_order, type } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute(
      'UPDATE categories SET name = ?, sort_order = ?, type = ? WHERE id = ?',
      [name, sort_order, type, id]
    );
    if (result.affectedRows === 0) {
      return sendResponse(res, 404, '分类未找到');
    }
    await connection.commit();
    sendResponse(res, 200, '更新分类成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '更新分类失败', error.message);
  } finally {
    connection.release();
  }
};

// 删除分类
const deleteCategory = async (req, res) => {
  const { id } = req.params;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查是否有关联菜品
    const [dishes] = await connection.execute('SELECT * FROM dishes WHERE category_id = ?', [id]);
    if (dishes.length > 0) {
      await connection.rollback();
      return sendResponse(res, 400, '该分类下有关联菜品，无法删除');
    }
    const [result] = await connection.execute('DELETE FROM categories WHERE id = ?', [id]);
    if (result.affectedRows === 0) {
      return sendResponse(res, 404, '分类未找到');
    }
    await connection.commit();
    sendResponse(res, 200, '删除分类成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '删除分类失败', error.message);
  } finally {
    connection.release();
  }
};

module.exports = {
  getAllCategories,
  getCategoryById,
  createCategory,
  updateCategory,
  deleteCategory
};